package java8;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Collectors练习
 */
public class CollectorsTest1 {
    public static void main(String[] args) {
        Map<String, List<String>> map = Stream.of(new MyDto("k1", "张三"), new MyDto("k1", "李四"), new MyDto("k2", "王小二"))
                .collect(Collectors.groupingBy(MyDto::getKey, Collectors.mapping(MyDto::getName, Collectors.toList())));
        System.out.println(map); // {k1=[张三, 李四], k2=[王小二]}

        Map<String, Optional<Integer>> map2 = Stream.of(new MyDto("k1", "张三三四"), new MyDto("k1", "李四"), new MyDto("k2", "王小二"))
                .collect(Collectors.groupingBy(MyDto::getKey, Collectors.mapping(MyDto::getName,
                        Collectors.mapping(String::length, Collectors.maxBy(Comparator.comparingInt(o -> o))))));
        System.out.println(map2); // {k1=Optional[4], k2=Optional[3]}
    }


    @AllArgsConstructor
    @Data
    private static class MyDto {
        String key;
        String name;

    }
}
